<?php
require "./common/function.php";
if($_POST){
//    接收订单相关信息
    $ids=$_POST['ids'];

//    生成订单信息，且此时订单状态为未支付
    $flag=false;
    $nids=array();
    foreach ($ids as $k=>$id){
//        拼接订单编号：商品编号_随机数时间戳
        $rand = $id.'_'.time();
        $nids[$k]=$rand;

        $proOrd=array();
        $sql2="select a.id,a.name,a.price,b.buynum from t_product a LEFT JOIN t_product_order b on a.id=b.pid where b.buynum is not NULL and a.id=$id and b.oid is null";
        $res = getMySql($sql2,'查询购物车信息失败');
        if($res){
            if(mysqli_num_rows($res)){
                $proOrd = mysqli_fetch_array($res,MYSQLI_ASSOC);
            }
        }
        $price = $proOrd['price'];
        $buyNums = $proOrd['buynum'];
        $money = $price*$buyNums;
//获取系统当前时间并进行格式化
        $date=date('Y-m-d h:i:s',time());
        $uid = $_COOKIE['uId'];

        $sql="INSERT INTO t_order(id,money,paystate,ordertime,userid)VALUES('$rand',$money,1,'$date',$uid)";
        $result=getMySql($sql,'订单生成失败');
        if($result){
            $flag=true;
        }else{
            $flag=false;
            break;
        }
    }
//    查商品信息
    $idStr = implode(",",$ids);//将Array数组以,的形式组合成字符串
    $selSql = "select a.id,a.name,a.price,b.buynum from t_product a LEFT JOIN t_product_order b on a.id=b.pid where b.buynum is not NULL and a.id in ($idStr) and b.oid is null";

    $selResult=getMySql($selSql,'查询购物车商品信息失败');
    if($selResult){
        if(mysqli_num_rows($selResult)){
            $proResult = mysqli_fetch_all($selResult,MYSQLI_ASSOC);
        }
    }
//    页面跳转
    if($flag){
        require "./html/addOrder.html";
    }else{
        $msg=[false,'订单失败'];
        require "./html/addProOrder.html";
    }
    exit;
}

require "./html/addOrder.html";
exit;
